using System;
using TMPro;
using UnityEngine;

namespace View.ViewComponent
{
    [RequireComponent(typeof(TMP_InputField))]
    public class IntFieldBinder : MonoBehaviour
    {

        public TMP_InputField BindForm;

        private int _curValue = 0;

        public event Action<int> OnValueChange;

        public int Value
        {
            get => this._curValue;
            set
            {
                this._curValue = value;
                this.BindForm.text = value.ToString();
            }
        }

        private void Awake()
        {
            if (this.BindForm == null)
                this.BindForm = this.GetComponent<TMP_InputField>();
            this.BindForm.onValueChanged.AddListener(this.OnUpdateValue);
            this.OnUpdateValue(this.BindForm.text);
        }

        private void OnUpdateValue(string arg0)
        {
            if (int.TryParse(arg0, out _curValue))
            {
                this.OnValueChange?.Invoke(_curValue);
            }
        }
    }
}